#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

int main(int argc, char *argv[]) {
    int fd;
    ssize_t nw, nr;
    off_t off;
    if (argc != 2) {
        printf("Usage: %s <file>\n", argv[0]);
        return 1;
    }

    fd = open(argv[1], O_WRONLY | O_CREAT | O_TRUNC, 0644);
    if (fd == -1) {
        perror("open");
        return 1;
    }
    nw = write(fd, "Hello, world!\n", 13);
    if (nw == -1) {
        perror("write");
        return 1;
    }
    printf("wrote %ld bytes\n", nw);
    fsync(fd);
    close(fd);

    // reopen the file with O_APPEND
    fd = open(argv[1], O_WRONLY | O_APPEND);
    if (fd == -1) {
        perror("reopen");
        return 1;
    }

    off = lseek(fd, 0, SEEK_CUR);
    if (off == -1) {
        perror("lseek");
        return 1;
    }
    printf("eof offset: %ld\n", off);
    off = lseek(fd, 0, SEEK_SET);
    if (off == -1) {
        perror("lseek");
        return 1;
    }
    off = lseek(fd, 0, SEEK_CUR);
    printf("rewind to start, current offset: %ld\n", off);

    nw = write(fd, "olleH", 5);
    if (nw == -1) {
        perror("write");
        return 1;
    }
    printf("wrote %ld bytes\n", nw);
    close(fd);

    char buf[32];
    fd = open(argv[1], O_RDONLY);
    if (fd == -1) {
        perror("open");
        return 1;
    }
    nr = read(fd, buf, 31);
    if (nr == -1) {
        perror("read");
        return 1;
    }
    buf[nr] = '\0';
    printf("read %ld bytes: %s\n", nr, buf);

    close(fd);
    return 0;
}